import React from 'react'
import { Checkbox,Tabs, Modal, error, Link, info, Button, success, TitleBar } from '../../ui-components'
import { u } from '../../actions/util'
import { connect } from 'react-redux'
import style from './style.staffProfile'
import UserProfile from '../personal/UserProfile'
import util from '../../util'
import cx from 'classnames'
import { bindActionCreators } from 'redux'
import { clearAtList, fetchAtList } from '../../actions/home.action'
import { updateAvatar, fetchAddresses } from '../../actions/app.action'
import { fetchRole, delStaff, createDocument, updateOnboardingFlowStatus } from '../../actions/onboarding.hr.action'
import { fileUpload } from '../../actions/file.action'
import * as userAction from '../../actions/user.action'
import * as teamAction from '../../actions/team.action'
import { ONBOARDING_STATUS } from '../onboarding/hr/OnboardingFlows'
import { help as styleHelp } from '../onboarding/staff/style.fill' 
import userStatusMap from '../../constants/userStatus'
import {TemplateMap,getFieldGroup}  from '../../constants/fieldsMap'

const employmentStatus_map = {
  1: '试用',
  2: '正式',
}

export default
@connect(({ user, app }) => ({ user, app }), dispatch => ({actions: bindActionCreators({...teamAction, ...userAction, clearAtList, fetchAtList, updateAvatar, fetchAddresses, createDocument, fileUpload, updateOnboardingFlowStatus, delStaff, fetchRole }, dispatch)}))
class extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      deleteStaff: false,
      sureOnboarding: false,
      cancelOnboarding: false,
      roles: [],
      sure: false,
      supplement: false,
      action: false
    }
  }

  updateRole() {
    info('更新中...')
    this.props.actions.updateUserRole(this.state.roles.filter(r => r.flag).map(r => ({ idValue: r.roleId })), this.props.params.userId, () => {
      success('更新成功!')
    })
  }

  handleTab(index) {

    const { location } = this.props
    const { query, pathname } = location

    this.props.router.push({
      pathname,
      query: {
        ...query,
        tab: index
      }
    })
  }

  componentWillReceiveProps(props) {
    if (this.props.params.userId != props.params.userId) {
      this.fetchContent(props)
    }

    if (props.location.query.tab != this.props.location.query.tab) {
      this.fetchContent(props)
    }

    if (props.user.roles.length && !this.props.user.roles.length) {
      this.setState({
        roles: props.user.roles
      })
    }
  }

  fetchContent(props) {
    props = props || this.props
    const { tab } = props.location.query

    this.fetchProfile(props)

    // basic
    //if (tab == 2) {
      this.props.actions.fetchRole(props.params.userId)
    //}
  }

  handleSubmit(stat) {
    info('提交中...')
    this.props.actions.updateOnboardingFlowStatus(this.props.params.userId, stat, () => {
      info()
      if( stat == 3) {
        this.setState({
          sureOnboarding: true
        })
      } else {
        this.setState({
          cancelOnboarding: true
        })
      }
      this.fetchProfile()
    })
  }

  fetchProfile(props) {
    props = props || this.props
    this.props.actions.fetchUserProfile(props.params.userId)
  }

  requestDeleteStaff() {
    this.setState({
      deleteStaff: true
    })
  }

  deleteStaff() {
    info('删除中...', true)
    this.props.actions.delStaff(this.props.params.userId, () => {
      success('删除成功!')
      const { teamVO } = this.props.app.org
      if ((teamVO || {}).teamId) {
        this.props.router.push(`/hr/index??teamId=${teamVO.teamId}`)
      }
    })
  }

  componentDidMount() {
    this.fetchContent()
  }

  componentWillUnmount() {
    this.props.actions.resetUser()
    util.unbind(document, 'click', this.closeAction)
  }

  handleSave(changed, cb) {
    const neededUpdate = changed || {};
    const { isTeamAdmin, contractType, fulltimeEnrollDate, fulltimeResignDate, internshipEnrollDate, internshipResignDate, parttimeEnrollDate, parttimeResignDate, ...others } = neededUpdate;
    //const { fullName, ...others } = neededUpdate;
    if (util.isNull(neededUpdate)) return

    let userEmploymentField = {}
    if (contractType != null) userEmploymentField.contractType = contractType 
    if (fulltimeEnrollDate != null) userEmploymentField.fulltimeEnrollDate = fulltimeEnrollDate;
    if (fulltimeResignDate != null) userEmploymentField.fulltimeResignDate = fulltimeResignDate;
    if (internshipEnrollDate != null) userEmploymentField.internshipEnrollDate = fulltimeEnrollDate;
    if (internshipResignDate != null) userEmploymentField.internshipResignDate = fulltimeResignDate;
    if (parttimeEnrollDate != null) userEmploymentField.parttimeEnrollDate = parttimeEnrollDate;
    if (parttimeResignDate != null) userEmploymentField.parttimeResignDate = parttimeResignDate;

    let teamAdmin = {}
    if(isTeamAdmin !== null) {
      teamAdmin.isTeamAdmin = +isTeamAdmin;
      teamAdmin.userId = this.props.params.userId;
    }

    const arr = []
    const checkSuccess = () => {
      arr.pop();
      if (!arr.length) {
        success('更新成功!');
        cb && cb();
      }
    };

    info('更新中...', true)
    if (!util.isNull(others)) {
      arr.push[1];
      this.props.actions.updateUserProfile(this.props.params.userId, others, () => {
        checkSuccess();
        if (changed.emailAddress) {
          if(this.props.params.userId == u.userId) {
            location.href = '/u'
          }
        }
      })
    }

    if (!util.isNull(userEmploymentField)) {
      arr.push[1];
      this.props.actions.updateUserEmployment(this.props.params.userId, userEmploymentField, () => {
        checkSuccess();
      }) 
    }

    if(!util.isNull(teamAdmin)) {
      this.props.actions.updateTeamAdmin(teamAdmin, () => {
        checkSuccess();
      })
    }
  }

  toggleRoles(id) {
    this.setState({
      roles: this.state.roles.map((r, i) => {
        if(r.roleId == id) {
          return {
            ...r,
            flag: !r.flag
          }
        }
        return r
      })
    })
  }

  renderRoleManage(index) {
    if (index !== 3) return null
    const { roles } = this.state
    if (util.isNull(roles)) return null
    return (
      <div className={style.roles}>
        <div>
        {
          roles.map((v, i) => (
            <Checkbox 
              disabled={!v.editable}
              active={v.flag}
              onClick={() => {
                if (v.editable) {
                  this.toggleRoles(v.roleId)
                }
              }}
              key={i}
              label={v.roleDesc}
            />
          ))
        }
        </div>
        <Button label="更新" className={style['update-role']} onClick={::this.updateRole}/>
      </div>
    )
  }

  requestSupplement() {
    this.setState({
      supplement: true
    })
  }

  requestSure() {
    this.setState({
      sure: true
    })
  }

  sure() {
    this.handleSubmit(3)
    this.setState({
      sure: false
    })
  }

  supplement() {
    this.handleSubmit(1)
    this.setState({
      supplement: false
    })
  }

  renderBasic(index) {

    const { profile: userProfile } = this.props.app
    const { roleNameList = [] } = userProfile
    const { profile={} } = this.props.user 
    const { userStatus, profileFieldVOs=[], userEmploymentVO={} } = profile
    const { onboardingStatus } = userEmploymentVO
    if (index !== 1) return null 

    const editable = v => {
      if (typeof v === 'object') {
        if (Object.hasOwnProperty.call(v, 'isEditable')) {
          if (~['contractType', 'enrollDate', 'resignDate'].indexOf(v.referenceName)) {


            let ret = {
              ...v,
              dataType: v._dataType,
              isEditable: true,
              dataValue: userEmploymentVO.contractType,
              userEmploymentVO
            };

            if (v._dataType == 4) {

              let realName = '';
              const { contractType } = userEmploymentVO
              const type = v.referenceName === 'resignDate'? 'Resign': 'Enroll';
              if (contractType == 1) realName = `internship${type}Date`;
              if (contractType == 2) realName = `parttime${type}Date`;
              if (contractType == 3) realName = `fulltime${type}Date`;

              ret = {
                ...ret,
                dataValue: userEmploymentVO[realName] || '',
                realName
              }
            }

            return ret
          }
        }
      }
      return v;
    };

    const templateMap = ~roleNameList.indexOf('HR')? TemplateMap.map(v => ({
      ...v,
      children: v.children.map(editable)
    })): TemplateMap

    const fields = getFieldGroup(templateMap, profileFieldVOs).filter((v)=>!!v.isManageOnly) || []
    return (
      <div>
        <div className={style.list}>
          <UserProfile
            fields={fields}
            fetchAddresses={this.props.actions.fetchAddresses}
            app={this.props.app}
            createDocument={this.props.actions.createDocument}
            fileUpload={this.props.actions.fileUpload}
            updateAvatar={this.props.actions.updateAvatar}
            onSave={::this.handleSave}
            userId={this.props.params.userId}
            userEmploymentVO={ (this.props.user.profile||{}).userEmploymentVO || {} }
            changeUserEmployment={field => {
              this.props.actions.changeUserEmployment({
                ...userEmploymentVO,
                ...field
              })
            }}
            label="更新"
            profileType={'staffProfile'}
          />
        </div>
      </div>
    )
  }
  renderInfo(index) {
    const { profile={} } = this.props.user 
    const { userStatus, profileFieldVOs=[], userEmploymentVO={} } = profile
    const { onboardingStatus } = userEmploymentVO
    // self
    if (util.isEqual(u.userId, this.props.params.userId)) {
      if (index !== 1) return null
    } else if (index !== 2) {
      return null 
    }
    return (
      <div>
        {
          onboardingStatus == 3 && this.state.sureOnboarding && (
            <div className={styleHelp}>
              <span>入职资料已确认。</span>
            </div>
          )
        }
        {
          onboardingStatus == 1 && this.state.cancelOnboarding && (
            <div className={styleHelp}>
              <span>入职资料已请求员工补充。</span>
            </div>
          )
        }
        {
          onboardingStatus == 2 && (
            <div className={styleHelp}>
              <span>该员工已经提交入职资料，请审核通过后确认其入职。</span>
              <Button label="确认入职资料" onClick={::this.requestSure}/>
              <Link label="请求补充" onClick={::this.requestSupplement}/>
            </div>
          )
        }
        <div className={style.list}>
          <UserProfile
            fields={getFieldGroup(TemplateMap, profileFieldVOs).filter((v)=>!v.isManageOnly)|| []}
            fetchAddresses={this.props.actions.fetchAddresses}
            app={this.props.app}
            createDocument={this.props.actions.createDocument}
            fileUpload={this.props.actions.fileUpload}
            updateAvatar={this.props.actions.updateAvatar}
            onSave={::this.handleSave}
            userId={this.props.params.userId}
            userEmploymentVO={ (this.props.user.profile||{}).userEmploymentVO || {} }
            label="更新"
            profileType={'staffProfile'}
          />
        </div>
      </div>
    )
  }

  handleAction() {
    this.setState({
      action: true
    })
    util.bind(document, 'click', this.closeAction)
  }

  closeAction = () => {
    this.setState({
      action: false
    })
    util.unbind(document, 'click', this.closeAction)
  }

  render() {
    const { profile={} } = this.props.user 
    const { userStatus, profileFieldVOs=[], userEmploymentVO={} } = profile
    const { onboardingStatus,employmentStatus,userStatus:userStatusByEmp } = userEmploymentVO
    const fullName = util.find(profileFieldVOs, field => field.referenceName === 'fullName').dataValue
    const { userId } = this.props.params
    let actions=[
      {
        label: "办理转正",
        handler: () => this.props.router.push(`/hr/reorg/employ-managements/1/${userId}`)
      },
      {
        label: "办理调岗",
        handler: () => this.props.router.push(`/hr/reorg/transfer/${userId}`)
      },
      {
        label: "办理离职",
        handler: () => this.props.router.push(`/hr/reorg/employ-managements/2/${userId}`)
      }
    ]
    // 离职
    actions.unshift({
      label: '删除员工',
      handler: ::this.requestDeleteStaff,
      link: true,
      color: 'red'
    })
    //暂时这么写
    let managable = 0;
    if(this.props.app){
      const {roleNameList = []} = this.props.app.profile || {}; 
      if(~roleNameList.indexOf('HR')) {
        managable = 1;
      }else if(~roleNameList.indexOf('orgAdmin')) {
        managable = 3;
      }
    }
    const index = this.props.location.query.tab || managable || 1;
    const { org } = this.props.app
    const { teamVO={} } = org
    const back = teamVO.teamId? { back: `/hr/index?teamId=${teamVO.teamId}` }: {}

    let tabs= [
      {
        label: '工作信息',
        disabled: managable === 3,
      },
      {
        label: '员工资料',
        disabled: managable === 3,
      }
    ]

    if (util.isEqual(u.userId, userId)) {
      tabs.shift();
    }
    return (
      <div style={{ paddingTop: '30px' }}>
        <TitleBar 
          {...back}
          label={fullName || ''}
          leftActions={[({ key }) => onboardingStatus? 
            <div key={key} className={style['title-tag']}>
              {'状态：'}
              <span>{userStatusMap(userEmploymentVO)}</span>
              <span>{employmentStatus_map[employmentStatus]}</span>
              <span>{ONBOARDING_STATUS[onboardingStatus]}</span>
            </div>
            : '']
          }
        >
          {
            !util.isEqual(u.userId, userId)?
            <Link icon="more" className={style.action} onClick={::this.handleAction}/>
            : null
          }
          {
            (this.state.action && !util.isEqual(u.userId, userId))?
            <ul className={style.actions}>
              {
                actions.map((v, i) => (
                  <li className={cx({ [style.red]: v.color == 'red' })} key={i} onClick={v.handler}>{v.label}</li>
                ))
              }
            </ul>: null
          }
        </TitleBar>
        <Tabs
          className={style.tabs}
          onChange={::this.handleTab}
          index={+index}
          top
          tabs={tabs}
        />
        { util.isEqual(userId, u.userId)? null: this.renderBasic(+index) }
        { this.renderInfo(+index) }
        { /*this.renderRoleManage(+index) */}
        <Modal
          active={this.state.deleteStaff}
          onRequestClose={() => this.setState({ deleteStaff: false })}
          actions={[
            'cancel',
            ::this.deleteStaff
          ]}
          title="删除员工"
        >
          <div>
            <p>确定要删除这个员工吗?</p>
          </div>
        </Modal>
        <Modal
          active={this.state.sure}
          onRequestClose={() => this.setState({ sure: false })}
          actions={[
            'cancel',
            ::this.sure
          ]}
          title="确认入职资料"
        >
          <div>
            <p>确认审核通过吗？</p>
          </div>
        </Modal>
        <Modal
          active={this.state.supplement}
          onRequestClose={() => this.setState({ supplement: false })}
          actions={[
            'cancel',
            ::this.supplement
          ]}
          title="请求补充"
        >
          <div>
            <p>确认请求员工补充？将重新向其发送入职邮件，要求员工补充完成后再次提交审核。</p>
          </div>
        </Modal>
      </div>
    )
  }
}
